/**
 * Using Rails-like standard naming convention for endpoints.
 * GET     /exams              ->  index
 * POST    /exams              ->  create
 * GET     /exams/:id          ->  show
 * PUT     /exams/:id          ->  update
 * DELETE  /exams/:id          ->  destroy
 */

'use strict';

var _ = require('lodash');
var Exam = require('./exam.model');

// Get list of exam
exports.index = function(req, res) {
  Exam.find({$query: {}, $orderby:{createtime: 1}},'-courses -content',function (err, exams) {
    if(err) { return handleError(res, err); }
    return res.json(200, exams);
  });
};
exports.getCounts = function(req, res) {
  var klasscode=req.params.klasscode;
  Exam.find({klass:klasscode}).count().exec(function (err, count) {
    if(err) { return handleError(res, err); }
    console.log("总个数：",count);
    return res.json(200, {count:count});
  });
};
//Get exams from klass code
exports.getFromKlasscode = function(req, res) {
  var klasscode=req.params.code;
  var pageindex=req.params.pageindex;
  var pagesize=req.params.pagesize;
  var options={sort:{createtime: -1}};
  if(pageindex){
    console.log("页码：",pageindex);
    options.skip=(pageindex-1)*pagesize;
    options.limit=pagesize;
  }
  console.log("options:",options);
  Exam.find({klass:klasscode},'-courses -content',options,function (err, exams) {
    if(err) { return handleError(res, err); }
    return res.json(200, exams);
  });
};
//Get exams from klass code newest exam
exports.getLastOne = function(req, res) {
  Exam.findOne({$query: {klass:req.params.code}, $orderby:{createtime: -1}},function (err, exam) {
    if(err) { return handleError(res, err); }
    return res.json(200, exam);
  });
};
// Get a single exam
exports.show = function(req, res) {
  Exam.findById(req.params.id, function (err, exam) {
    if(err) { return handleError(res, err); }
    if(!exam) { return res.send(404); }
    return res.json(exam);
  });
};

// Creates a new exam in the DB.
exports.create = function(req, res) {
  //console.log(req.body);
  Exam.create(req.body, function(err, exam) {
    if(err) { return handleError(res, err); }
    //console.log(exam);
    return res.json(201, exam);
  });
};

// Updates an existing exam in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  //console.log(req.body._id,req.params.id);
  Exam.findById(req.params.id, function (err, exam) {
    if (err) { return handleError(res, err); }
    if(!exam) { return res.send(404); }
    //console.log(JSON.stringify(req.body));
    var updated = _.assign(exam, req.body);
    //console.log(JSON.stringify(updated));
    updated.markModified('courses');
		updated.markModified('content');
		//好大的陷阱，反直觉的设计，mongoose对于Mixed, {}, Array, []无法检查是否更改，因此
		//Any field in your schema with a type of either: Mixed, {}, Array, [] require the use of markModified when its contents are changed
		//http://stackoverflow.com/questions/14922311/mongoose-update-embedded-document-does-not-work
		//http://mongoosejs.com/docs/schematypes.html
		//http://mongoosejs.com/docs/faq.html
		// 3.2.0
		// doc.array.set(3, 'changed');
		// doc.save();
		//
		// // if running a version less than 3.2.0, you must mark the array modified before saving.
		// doc.array[3] = 'changed';
		// doc.markModified('array');
		// doc.save();
    //console.log(JSON.stringify(updated));
    updated.save(function (err,data) {
      if (err) { return handleError(res, err); }
      //console.log(JSON.stringify(data));
      return res.json(200, data);
    });
  });
};

// Deletes a exam from the DB.
exports.destroy = function(req, res) {
  console.log(req.params.id);
  Exam.findById(req.params.id, function (err, exam) {
    if(err) { return handleError(res, err); }
    if(!exam) { return res.send(404); }
    console.log(exam);
    exam.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}
